import { SyncOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import styles from '../index.less';
import { Button, Icon, DatePicker, Radio, notification, Input, Modal } from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useBoolean, useRequest } from '@umijs/hooks';
import { getTableList, getProposerById, examineData, resetActAuditInfo, lookActAuditInfo, qucklyPay } from '../service';
import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';
import CheckList from './CheckList';
import VerifyStep from './VerifyStep/index';


const { confirm } = Modal;

let hiddenData = null;
const ApplicationList = (props) => {

  const { location: {state} } = props;

  const { handleAnimation, handleReceiveData, setPaytypeVlaue,setRightModelLoading } = props;

  // 禁用审核按钮
  const { state: checkState, setTrue: checkTrue, setFalse: checkFalse } = useBoolean(true);
  // 撤回按钮禁用
  const { state: resetState, setTrue: resetTrue, setFalse: resetFalse } = useBoolean(true);
  // 禁用快速支付
  const { state: payState, setTrue: payTrue, setFalse: payFalse } = useBoolean(true);
  // 审核旅客弹框
  const [modalVisible, handleModal] = useState(false);
  // 审核流程弹框
  const [modalVisibleH, handleVerify] = useState(false);

  // 航班号
    const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }
  // 切换清空搜索
  useEffect(() => {
    hiddenData = null
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state])

  // 表格高度
  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 364.5);
    } else {
      controlH(document.body.clientHeight - 420.5);
    }
  }, [isCollapse])

  // 防止多次请求
  const [inited, setInited] = useState(false);
  // 第一次加载
  const [firstLoadDate, setFirstLoadDate] = useState(true)
  const [firstLoadApplyDate, setFirstLoadApplyDate] = useState(true)

  const actionRef = useRef();
  const searchRef = useRef();
  const ref = useRef();

  const reloadTable = useCallback(function reloadData() {
    handleTableSelectData([]);
    if (searchRef.current) {
      searchRef.current.click();
    }

  }, []);

  const onScopeChange = useCallback(e => {
    setDataScope(e.target.value);
    handleAnimation(false);
    reloadTable();
    checkTrue();
    resetTrue();
    payTrue();
    // 清空选择项
    actionRef.current&&actionRef.current.clearSelected();
  }, []);

  // 切换审核类型
  const [dataScope, setDataScope] = useState('0');

  useEffect(() => {
    if (actionRef.current && inited) {
      reloadTable();
    } else {
      setInited(true)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataScope])


    // 从消息页跳转过来，初始化加载查询参数
    useEffect(()=>{
      if (ref.current && state && sessionStorage.getItem('firstLoad')){
        setDataScope('')
        // console.log('state.....', state);
        ref.current.setFieldsValue({
          startDate: state.flightDate ? moment(state.flightDate) : '',
          endDate: state.flightDate ? moment(state.flightDate) :'',
          flightNo: state.flightNo ? state.flightNo : '',
          applyStartDate: state.sendDate ? moment(state.sendDate) : '',
          applyEndDate: state.sendDate ? moment(state.sendDate) : '',
          applyCode: state.applyCode ? state.applyCode : '',
        })
        reloadTable();
        sessionStorage.removeItem('firstLoad')
      }
    }, [ref.current])

  // 记录审核数据
  const [historyData, hanldeHistoryData] = useState([]);

  //  审核旅客信息
  const checkList = () => {
    runExamine({
      applyCode: tableSelectData.join(',')
    })
    handleModal(true);
  }

  const beforeSearchSubmit = useCallback(params => {
    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';
    params['applyStartDate'] = params.applyStartDate ? params.applyStartDate.format('YYYY-MM-DD') : '';
    params['applyEndDate'] = params.applyEndDate ? params.applyEndDate.format('YYYY-MM-DD') : '';

    if (event&&event.target&&event.target.querySelector && event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
      if (Object.keys(params).indexOf('startDate') === -1) {
        params.startDate = '';
      }
      if (Object.keys(params).indexOf('endDate') === -1) {
        params.endDate = '';
      }
    } else if (event&&event.target&&event.target.querySelector && event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
      ref.current.setFieldsValue({
        startDate: moment(),
        endDate: moment(),
        applyStartDate: moment(),
        applyEndDate: moment(),
      });
    }
    return { ...params, queryType: dataScope }
    
  }, [dataScope]);

  // 根据申领单号获取申领人信息
  const { run, loading:loadingRightModel } = useRequest((params) => getProposerById(params), {
    manual: true,
    onSuccess: data => {
      handleReceiveData(data);
    }
  })

  useEffect(() => {
    setRightModelLoading(loadingRightModel);
  }, [loadingRightModel])

  // 审核接口
  const { loading: loadingExamine, run: runExamine } = useRequest((params) => examineData(params), {
    manual: true,
    onSuccess: data => {
      handlePersonInfo(data)
    }
  })

  // 撤回接口
  const { loading: loadingReset, run: runReset } = useRequest((data) => resetActAuditInfo(data), {
    manual: true,
    onSuccess: data => {
      if (data) {
        notification.success({
          message: '成功',
          duration: 3,
          description: '操作完成'
        })
      }
      actionRef.current.reload();
      checkTrue();
      resetTrue();
      payTrue();
    }
  })
  
  // 快速支付接口
  const { loading: loadingPay, run: runPay } = useRequest((params) => qucklyPay(params), {
    manual: true,
    onSuccess: data => {
      notification.success({
        message: '成功',
        duration: 3,
        description: '操作完成'
      })
      actionRef.current.reload();
      checkTrue();
      resetTrue();
      payTrue();
    }
  })

  // 审核记录
  const { run: runHistory } = useRequest((params) => lookActAuditInfo(params), {
    manual: true,
    onSuccess: data => {
      hanldeHistoryData(data)
    }
  })
  // 撤回按钮
  const resetCompensation = () => {
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div style={{ fontSize: "16px" }}><span style={{ color: "#ff5a5a" }}>确认操作后，此补偿单将被撤回，</span> 你还要继续吗？</div>
      ),
      onOk() {
        runReset({
          applyCode: tableSelectData.join(',')
        })
      }
    });
  }
  // 快速支付
  const fastPay = () => {
    if (tableSelectDataArr[0].quickPay != '0') {
      return notification.error({
        message: '失败',
        duration: 3,
        description: '您当前操作的申领单已进入支付环节，无须快速支付'
      })
    }
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div style={{ fontSize: "16px" }}><span style={{ color: "#ff5a5a" }}>您当前操作的申领单在等待支付时间范围内，操作后，将直接进行支付。</span> 请确认是否直接进入支付环节？</div>
      ),
      onOk() {
        runPay({
          applyCode: tableSelectData.join(',')
        })
      },
      closable: true
    });
  }

  // 表格选中数据id;
  const [tableSelectData, handleTableSelectData] = useState([]);
  // 表格选中数据id;
  const [tableSelectDataArr, handleTableSelectDataArr] = useState([]);
  // 被审核人员信息
  const [examinePersonInfo, handlePersonInfo] = useState(null);

  const rowSelection = {
    selectedRowKeys:tableSelectData,
    onChange: (a, b) => {
      handleTableSelectData(a);
      handleTableSelectDataArr(b);
      if (a.length === 1 && (b&&b[0].applyStatus === '0')) {
        checkFalse();
      } else {
        checkTrue();
      }

      if (a.length === 1 && (b&&b[0].applyStatus === '1' || b&&b[0].applyStatus === '2') && (b&&b[0].payStatus !== '1' && b&&b[0].payStatus !== '2')) {
        resetFalse();
      } else {
        resetTrue();
      }
      if (a.length === 1 && (b&&b[0].applyStatus === '1') && (b&&b[0].payStatus === '0')) {
        payFalse();
      } else {
        payTrue();
      }
    }
  }
  const columns = [
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 50,
      // hideInTable: !(AuthComponent.getAuth('substitutePassenger.index.showAudit')),
      render: (_, record) => [
        // <AuthComponent authCode="substitutePassenger.index.showAudit">
          <span onClick={(e) => {
            e.stopPropagation();
            runHistory({
              applyCode: record.applyCode
            })
            handleVerify(true);
          }} style={{ cursor: "pointer" }}>
            <SyncOutlined />
          </span>,
        //  </AuthComponent> 
      ],
    },
    {
      title: '申领单号',
      dataIndex: 'applyCode',
      width: 160,
      // hideInSearch: true,
      // hideInTable: true,
    },
    {
      title:"补偿类型",
      width:120,
      dataIndex:"payType",
      filters:[
        { text: '不正常航班', value: '0' },
        { text: '异常行李', value: '1' },
        { text: '旅客超售', value: '2' },
      ],
      valueEnum:{
        '': { text: '全部'},
        "0":{text:"不正常航班"},
        "1":{text:"异常行李"},
        "2":{text:"旅客超售"},
      }
    },
    {
      width: 120,
      title: '审核状态',
      dataIndex: 'applyStatus',
      filters: [
        { text: '待审核', value: '0' },
        { text: '已通过', value: '1' },
        { text: '未通过', value: '2' },
        // { text: '失效', value: '3' },
        // { text: '冻结', value: '4' },
      ],
      valueEnum: {
        '': {
          text: '全部'
        },
        '0': {
          text: '待审核'
        },
        '1': {
          text: '已通过'
        },
        '2': {
          text: '未通过'
        },
        // '3': {
        //   text: '失效'
        // },
        // '4': {
        //   text: '冻结'
        // },
      }
    },
    {
      width: 120,
      title: '支付状态',
      dataIndex: 'payStatus',
      filters: [
        { text: '未支付', value: '0' },
        { text: '支付成功', value: '1' },
        { text: '支付失败', value: '2' },
        // { text: '处理中', value: '3' }
      ],
      valueEnum: {
        '0': {
          text: '未支付'
        },
        '1': {
          text: '支付成功'
        },
        '2': {
          text: '支付失败'
        },
        // '3': {
        //   text: '处理中'
        // },
        '': {
          text: '全部'
        }
      },
      render: (text, record) => <div>{record.quickPay === '1' ? <Icon type="thunderbolt" /> : null}<span>{text}</span></div>
    },
    {
      title: '申领人',
      dataIndex: 'applyUser',
      width: 100,
      order: 5,
    },
    {
      title: '代领人数',
      dataIndex: 'applyCustNum',
      hideInSearch: true,
      width: 100
    },
    {
      title: '申领金额',
      dataIndex: 'transAmount',
      hideInSearch: true,
      width: 100
    },
    {
      title: '联系电话',
      dataIndex: 'telephone',
      hideInSearch: true,
      width: 120
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      width: 200,
      hideInSearch: true,
      renderFormItem: (_, { ...rest }, form) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker.RangePicker
            format={format}
            {...rest}
          />
        );
      }
    },
    {
      title: '申请开始日期',
      hideInTable: true,
      dataIndex: 'applyStartDate',
      order: 4,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '申请结束日期',
      hideInTable: true,
      dataIndex: 'applyEndDate',
      order: 3,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      order: 6,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input 
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      },
      width: 100
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 120,
      hideInSearch: true
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 8,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      order: 7,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '领取方式',
      dataIndex: 'getMoneyWay',
      hideInSearch: true,
      filters: [
        { text: '微信', value: '0' },
        { text: '银联', value: '1' },
        { text: '支付宝', value: '2' },
        { text: '优惠券', value: '3' },
        { text: '现金', value: '4' },
      ],
      valueEnum: {
        '0': { text: '微信' },
        '1': { text: '银联' },
        '2': { text: '支付宝' },
        '3': { text: '优惠券' },
        '4': { text: '现金' },
      },
      width: 120
    },
    {
      title: '领取时间',
      dataIndex: 'receiveTime',
      hideInSearch: true,
      width: 150
    },
    {
      title: '账户',
      dataIndex: 'getMoneyAccount',
      hideInSearch: true,
      width: 280
    },
    {
      title: '开户名',
      dataIndex: 'khm',
      hideInSearch: true,
      width: 100,
      render: (text, record) => {
        if (record.getMoneyWay === '1') {
          return <span>{text}</span>
        }
      }
    },
    {
      title: '开户银行',
      dataIndex: 'openBank',
      hideInSearch: true,
      width: 150
    },
  ];
  return (
    <div className={styles.leftTable}>
      <ProTable
        options={{density: false, fullScreen: true, reload:false, setting: true }}
        tableAlertRender={false}
        formRef={ref}
        size='small'
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        className={`rest-pro-table-form-compact ${isCollapse ? '' : 'collapse'}`}
        scroll={{ x: 1000, y: height }}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>申请列表</span>
            <Radio.Group onChange={onScopeChange} value={dataScope} buttonStyle="solid">
              <Radio.Button value="">全部</Radio.Button>
              <Radio.Button value="0">待审核</Radio.Button>
              <Radio.Button value="1">已审核</Radio.Button>
            </Radio.Group>
          </div>
        }
        actionRef={actionRef}
        rowKey="applyCode"
        toolBarRender={(action, { selectedRows }) => [
          <>
            {/* 点击审核时，需要判断单子是否冻结或者失效，如果是，提出弹窗，见原型 */}
            <AuthComponent authCode="substitutePassenger.index.audit">
              <Button disabled={checkState} onClick={checkList} icon="check-circle" type="primary">审核</Button>
            </AuthComponent>
            <AuthComponent authCode="substitutePassenger.index.reset">
              <Button loading={loadingReset} onClick={resetCompensation} disabled={resetState} style={{ margin: "0 10px" }} icon="rollback" type="primary">撤回</Button>
            </AuthComponent>
            <AuthComponent authCode="substitutePassenger.index.payQuick">
              <Button onClick={fastPay} disabled={payState} loading={loadingPay} icon="money-collect" type="primary">快速支付</Button>
            </AuthComponent>
          </>
        ]}
        beforeSearchSubmit={beforeSearchSubmit}
        search={{
          searchText: (
            <span ref={searchRef}>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val);
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     flightNo: hiddenData['flightNo'],
            //     applyUser: hiddenData['applyUser'],
            //     payStatus: hiddenData['payStatus'],
            //     applyStatus: hiddenData['applyStatus'],
            //     payType: hiddenData['payType'],
            //     applyStartDate: hiddenData['applyStartDate'] ? moment(hiddenData['applyStartDate']) : '',
            //     applyEndDate: hiddenData['applyEndDate'] ? moment(hiddenData['applyEndDate']) : '',
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          }
        }}
        postData={(data) => {
          return data.map(v => {
            return { ...v, khm: v.applyUser }
          })
        }}
        columns={columns}
        rowSelection={rowSelection}
        onRow={record => {
          return {
            onClick: event => {
              if (AuthComponent.getAuth('substitutePassenger.index.showPax')) {
                run({
                  applyCode: record.applyCode
                })
                setPaytypeVlaue(record.payType);
                handleAnimation(true);
              }
            }
          }
        }}
        request={params => {
          // console.log('request....', params);
          params['queryType'] = dataScope;
          if (!params['startDate'] && !params['endState'] && firstLoadDate) {
            setFirstLoadDate(false)
            params['startDate'] = moment().format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment(),
              endDate: moment()
            })
          }
          if (!params['applyStartDate'] && !params['applyEndDate'] && firstLoadApplyDate) {
            setFirstLoadApplyDate(false)
            params['applyStartDate'] = moment().format('YYYY-MM-DD');
            params['applyEndDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              applyStartDate: moment(),
              applyEndDate: moment()
            })
          }
        
          if (!params['flightNo']) {
            ref.current.setFieldsValue({
              flightNo: ''
            })
          }
          if (!params['applyUser']) {
            ref.current.setFieldsValue({
              applyUser: ''
            })
          }
          if (!params['payStatus']) {
            ref.current.setFieldsValue({
              payStatus: ''
            })
          }
          if (!params['applyStatus']) {
            ref.current.setFieldsValue({
              applyStatus: ''
            })
          }
          if (!params['payType']) {
            ref.current.setFieldsValue({
              payType: ''
            })
          }
          // console.log('request后', params);
          return getTableList(params)
        }}

      />
      <CheckList {...{ examinePersonInfo, modalVisible, handleModal, loadingExamine, reloadTable, checkTrue, resetTrue, payTrue }} />
      <VerifyStep {...{ historyData, modalVisibleH, handleVerify }} />
    </div>
  )
}

export default Form.create()(ApplicationList);
